package com.cyz.api.imagesearch.sub;


import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.cyz.exception.BusinessException;
import com.cyz.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取图片页面 url
 */
@Slf4j
public class GetImagePageUrlApi {


    /**
     * 获取以图搜图页面地址
     */
    public static String getImagePageUrl(String imageUrl){

        // 1.1 准备请求参数
        Map<String, Object> requestParam = new HashMap<>();

        requestParam.put("image", imageUrl);
        requestParam.put("tn", "pc");
        requestParam.put("from", "pc");
        requestParam.put("image_source", "PC_UPLOAD_URL");

        // 1.2 获取时间戳
        long uptime = System.currentTimeMillis();

        // 1.3 拼接请求地址，获取请求url
        String url = "https://graph.baidu.com/upload?uptime=" + uptime;

        try{

            // 2.1 发起请求
            HttpResponse response = HttpRequest.post(url)
                    .header("acs-token", RandomUtil.randomString(1))
                    .form(requestParam)
                    .timeout(5000)
                    .execute();

            // 2.2 判断响应状态
            if (response.getStatus() != HttpStatus.HTTP_OK){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }
            // 2.3 解析请求，获取响应结果
            String responseBody = response.body();
            Map<String, Object> result = JSONUtil.toBean(responseBody, Map.class);

            if (result == null || !Integer.valueOf(0).equals(result.get("status"))){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "接口调用失败");
            }


            // 3.1 解析响应数据data
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            // 获取url
            String rawUrl = (String) data.get("url");

            // 解码
            String searchResultUrl = URLUtil.decode(rawUrl, StandardCharsets.UTF_8);

            // 如果 URL 为空
            if (searchResultUrl == null){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "未返回有效的结果");
            }
            // 返回结果
            return searchResultUrl;

        } catch (Exception e) {
            log.info("错误信息", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "搜索失败");
        }
    }

    /**
     * 测试方法
     */
    public static void main(String[] args) {

        String imagePageUrl = getImagePageUrl("https://beifeng-1368922749.cos.ap-beijing.myqcloud.com/space/1946899528809046018/2025-07-21_RffiYevdzGZYZHub.webp");
        System.out.println(imagePageUrl);

    }

}
